function getOrDefault (key, dvl = {}) {
  return get(key) ? get(key) : dvl
}

function set (key, val, expired) {
  localStorage.setItem(key, JSON.stringify(val))
  // 把过期时间存到 sessionStorage
  if (expired){
    sessionStorage.setItem(`${key}__expires__`, Date.now() + 1000 * expired)
  }
}

function get (key) {
  let expired = sessionStorage.getItem(`${key}__expires__`) || Date.now + 1;
  let now = Date.now();
  if (now >= expired) {
    remove(key);
    return null;
  }
  return JSON.parse(localStorage.getItem(key))
}

function remove (key) {
  localStorage.removeItem(key)
  sessionStorage.removeItem(`${key}__expires__`)
}

export {
  getOrDefault, set, get, remove
}

export default {
  getOrDefault: getOrDefault,
  set: set,
  get: get,
  remove: remove
}
